# ~*~ coding: utf-8 ~*~
import os
import os.path as osp
import shutil

from svn import remote
from svn import local
from svn.exception import SvnException


class SVN:

    def __init__(self, url, username, password):
        self.url = url
        self.username = username
        self.password = password
        self.path = None

    def is_svn_dir(self):
        d = os.path.join(self.path, '.svn')
        if osp.isdir(d):
            return True
        return False

    def init(self, path, is_need_clone=False):
        self.path = path
        if os.path.exists(self.path):
            shutil.rmtree(self.path, ignore_errors=True)
        if is_need_clone:
            remote_repo = remote.RemoteClient(self.url, username=self.username, password=self.password)
            remote_repo.checkout(self.path)

    def checkout_2_branch(self, branch):
        if os.path.exists(self.path):
            shutil.rmtree(self.path, ignore_errors=True)

        full_url = os.path.join(self.url, 'branches', branch)
        remote_repo = remote.RemoteClient(full_url, username=self.username, password=self.password)
        remote_repo.checkout(self.path)

    def checkout_2_commit(self, branch, commit):
        if os.path.exists(self.path):
            shutil.rmtree(self.path, ignore_errors=True)

        if branch:
            full_url = os.path.join(self.url, 'branches', branch)
        else:
            full_url = os.path.join(self.url, 'trunk')
        remote_repo = remote.RemoteClient(full_url, username=self.username, password=self.password)
        remote_repo.checkout(self.path, commit)

    def checkout_2_tag(self, tag):
        if os.path.exists(self.path):
            shutil.rmtree(self.path, ignore_errors=True)

        full_url = os.path.join(self.url, 'tags', tag)
        remote_repo = remote.RemoteClient(full_url, username=self.username, password=self.password)
        remote_repo.checkout(self.path)

    def branches(self):
        """
        获取所有分支
        @return:
        """
        try:
            local_repo = local.LocalClient(self.path, username=self.username, password=self.password)
            branch_list = local_repo.list(rel_path='branches')
            branches = [branch.rstrip('/') for branch in branch_list]
        except SvnException:
            branches = []
        return branches

    def tags(self):
        """
        获取所有tag，按时间倒序
        @return:
        """
        try:
            local_repo = local.LocalClient(self.path, username=self.username, password=self.password)
            tag_list = local_repo.list(rel_path='tags')
            tags = [tag.rstrip('/') for tag in tag_list]
        except SvnException:
            tags = []
        return tags

    def commits(self, branch=None):
        """
        获取svn仓库的revision
        :param branch: branch为None时：为master的版本号
        :return:
        """
        commits = []
        if not branch:
            real_path = None
        else:
            real_path = os.path.join('branches', branch)

        local_repo = local.LocalClient(self.path, username=self.username, password=self.password)
        for l in local_repo.log_default(rel_filepath=real_path, limit=20):
            commits.append({'id': l.revision, 'name': l.author, 'message': l.msg})
        return commits


if __name__ == '__main__':
    svn = SVN(url='svn://192.168.1.50/xafc-test/test', username='admin', password='Ddhi1lmi')

    # svn.init(path='/tmp/bees/test/svn', is_need_clone=True)
    # print('branches-->', svn.branches())
    # print('tags-->', svn.tags())
    # print('commits-->', svn.commits())
    # print('commits-->', svn.commits('dev_v2.0_bugfix'))

    svn.init(path='/tmp/bees/test/svn', is_need_clone=False)
    print('checkout_2_tag-->', svn.checkout_2_tag('v2.0'))
    # print('checkout_2_branch-->', svn.checkout_2_branch('dev_v1.0_bugfix'))
    # print('checkout_2_commit-->', svn.checkout_2_commit('dev_v1.0_bugfix', 16490))
    # print('checkout_2_commit-->', svn.checkout_2_commit(None, 17698))
